<?php

namespace Yjius\openapi\wangyihao;

use Yjius\common\CurlHelper;

class WangYiHaoOauth
{
    //应用参数
    private $client_id = null;
    private $client_secret = null;
    private $redirect_uri = null;

    const GET_CATEGORY_URL = 'http://mp.163.com/oauth2/article/category/get.do';
    const POST_ARTICLE_URL = 'http://mp.163.com/wemedia/article/status/api/oauth2/publish.do';

    //最外层初始化时，YII_ENV 可以选择不同的应用
    public function __construct($config = [])
    {
        //裁入配置
        $this->client_id = $config['client_id'] ?: '';
        $this->client_secret = $config['client_secret'] ?: '';
        $this->redirect_uri = $config['redirect_uri'] ?: '';
        if (empty($this->client_id) || empty($this->client_secret) || empty($this->redirect_uri)) {
            throw new \Exception("载入配置错误，请检查参数是否正确");
        }
    }

    /**
     * 返回【第一步：请求CODE】的url
     * Purpose: 认证跳转地址
     * Author:yingjiusheng@gsdata.cn
     * @date 2021/10/8 16:18
     */
    public function getCodeUrl()
    {
        $url = 'https://mp.163.com/oauth2/authorize?client_id=' . $this->client_id .
            '&response_type=code&redirect_uri=' . urlencode($this->redirect_uri);
        return $url;
    }

    /**
     * 第二步：通过code获取access_token
     * @param $code
     * @return bool|mixed|string
     */
    public function getAccessToken($code)
    {
//        http://mp.163.com/developer.html#/documents
//        https://mp.163.com/oauth2/access_token?client_id= YOUR_CLIENT_ID &client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&code=YOUR_CODE
        $url = 'https://mp.163.com/oauth2/access_token?client_id=' . $this->client_id
            . '&client_secret=' . $this->client_secret . '&grant_type=authorization_code&code=' . $code;
        $res = CurlHelper::httpRequest($url, [], 'post');
        return json_decode($res, true);
    }

    /**
     * 第三步：获取用户信息、网易号官方没有提供
     */

    /**
     * Purpose: 发布到网易号
     * Author:yingjiusheng@gsdata.cn
     * @date 2022/7/26 17:44
     */
    public function publish($accessToken, $articleOne)
    {
        //获取网易新闻分类
        //$cateArr = $this->getWangYiCategory();
        $params = array(
            'access_token' => $accessToken,
            'title' => $articleOne['title'],
            'content' => $articleOne['content'],
            "user_classify" => '要闻',
        );
        $coverImages = $articleOne['thumbnailList'];
        if (empty($coverImages)) {
            $params['cover'] = 'auto';
            $params['pic_url'] = '';
        }
        if (!empty($coverImages) && count($coverImages) == 1) {
            $params['cover'] = 'custom';
            $params['pic_url'] = $coverImages[0];
        }
        if (!empty($coverImages) && count($coverImages) > 1) {
            $params['cover'] = 'threeImg';
            $params['pic_url'] = implode(',', $coverImages);
        }
        $res = CurlHelper::httpRequest(self::POST_ARTICLE_URL, [], 'post', $params);
        $res = json_decode($res, true);
        if (isset($res['code']) && $res['code'] == '1') {
            // 发送成功
            return $res;
        } else {
            // 发送失败
            throw new \Exception($res['msg']);
        }
    }

    /**
     * Purpose: 网易号分类
     * Author:yingjiusheng@gsdata.cn
     * @date 2021/8/25 15:30
     */
    public function getWangYiCategory()
    {
        $url = self::GET_CATEGORY_URL . '?client_id=' . $this->client_id . '&client_secret=' . $this->client_secret;
        $res = CurlHelper::httpRequest($url);
        $res = json_decode($res, true);
        return $res;
    }
}